package net.uman.web.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class FileUploadUtils {
	private static final int BUFFER_SIZE = 16 * 1024;
	/**
	 * 复制文件到服务器上
	 * @param src
	 * @param dst
	 */
	public static void copy(File src, File dst) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(src);
			out = new FileOutputStream(dst);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 获取文件随机不可重复的文件名
	 * 
	 * @param file
	 * @return
	 */
	public static String getFilePathName(String target,String name) {
		String today = new SimpleDateFormat("yyMMdd").format(new Date());
		if (name.indexOf(".") > 0) {
			return "upload/"+target+"/"+ today + "/"+ UUID.randomUUID().toString()
					+ name.substring(name.lastIndexOf("."));
		}
		return "upload/"+target+"/"+ today + "/"+UUID.randomUUID().toString();
	}
	/**
	 * 上传
	 * 
	 * @param file
	 * @return
	 */
	public static String upload(String target,String fileName,File file) {
		String filePathName = getFilePathName(target, fileName);
		
		File dstFile = new File(filePathName);
        File parent = dstFile.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        
        copy(file, dstFile);
        
		return filePathName;
	}
	
	
}
